<?php

class Application_Model_Mapper_LastmessageMapper
{
	protected $_dbTable;

	public function setDbTable ($dbTable)
	{
		
		if (is_string($dbTable))
		{
			$dbTable = new $dbTable();
		}
		if (! $dbTable instanceof Zend_Db_Table_Abstract)
		{
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
		
	}

	public function getDbTable ()
	{
		if (null === $this->_dbTable)
		{
			$this->setDbTable('Application_Model_DbTable_Lastmessage');
		}
		return $this->_dbTable;
		
	}

	public function add (Application_Model_Lastmessage $lastmessage)
	{		
		$now = new DateTime();
		
		$generatedid = Helper_Idgenerator::getid();
		$generatedidcheck = $this->fetchID($generatedid);
		if(empty($generatedidcheck)){
			$data = array(
					'id' => $generatedid,
					'userID' => $lastmessage->getUserid(),
					'text' => $lastmessage->getText(),
					'created' => date('Y-m-d H:i:s'),				
			);
	
			return $this->getDbTable()->insert($data);
		}
		else{
			$this->add($lastmessage);
		}
	}
	
	public function addstring($message, $userid)
	{
		$now = new DateTime();
	
		$generatedid = Helper_Idgenerator::getid();
		$generatedidcheck = $this->fetchID($generatedid);
		if(empty($generatedidcheck)){
			$data = array(
					'id' => $generatedid,
					'userID' => $userid,
					'text' => htmlentities($message),
					'created' => date('Y-m-d H:i:s')
			);
			return $this->getDbTable()->insert($data);
		}
		else{
			$this->addstring($message, $userid);
		}
	}

	public function delete ($id)
	{
		$table = $this->getDbTable();
		$where = $table->getAdapter()->quoteInto('id = ?', $id);
		$table->delete($where);
	}


	public function fetchID($id)
	{
		$db = Zend_Db_Table::getDefaultAdapter();
		$entry = new Zend_Db_Select($db);
		$entry->from('lastmessage');
		$entry->where('lastmessage.id = ?', $id);
		return $entry->query()->fetch();
	}

	public function fetchUserID($id)
	{
 		$db = Zend_Db_Table::getDefaultAdapter();
 		$entry = new Zend_Db_Select($db);
		$entry->from('lastmessage');
		$entry->where('lastmessage.userID = ?', $id);
		$entry->limit(3);
		$entry->order('created DESC');
		return $entry->query()->fetchall();
	}
}




